package com.example.musicplayer.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.example.musicplayer.MusicPlayerApplication;
import com.example.musicplayer.R;
import com.example.musicplayer.commonUtils.StringUtil;
import com.example.musicplayer.commonUtils.ToastUtil;
import com.example.musicplayer.dialogTools.NormalAlertDialog;
import com.example.musicplayer.musicClass.MusicInfo;
import com.example.musicplayer.provider.DBConstants;
import com.example.musicplayer.user.UserManage;
import com.example.musicplayer.windowTools.WindowTools;

public class LoginActivity extends BaseActivity {
    private static final int NAME_LENGTH_LIMIT = 20;
    public static final String FORGET_PASSWORD = "forgetPassword";
    private EditText mUserName;
    private EditText mPassword;
    private TextView mUserNameLimit;
    private Button mLoginButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        WindowTools.lightStatusBar(getWindow());

        initView();
        addListener();
        mUserNameLimit.setText(String.valueOf(NAME_LENGTH_LIMIT));
        setUserNameIfExist();
    }

    private void setUserNameIfExist() {
        String name = UserManage.existUser(UserManage.getLastUserId());
        if (name != null) {
            mUserName.setText(name);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RegisterActivity.RESULT_CODE && data != null) {
            mUserName.setText("");
            mPassword.setText("");
            String name = data.getStringExtra(DBConstants.User.NAME);
            int id = data.getIntExtra(DBConstants.User.ID, -1);
            if (name == null || id == -1) {
                showErrorDialog(getString(R.string.register_fail));
            } else {
                mUserName.setText(name);
                showRegisterSuccessDialog(id);
            }
        }
    }

    @Override
    public void onBackPressed() {
        MusicPlayerApplication.getInstance().exit();
    }

    private void initView() {
        mUserName = findViewById(R.id.login_input_user_name);
        mPassword = findViewById(R.id.login_input_password);
        mUserNameLimit = findViewById(R.id.login_user_name_limit);
        mLoginButton = findViewById(R.id.login_in);
    }

    private void addListener() {
        mLoginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tryLogin();
            }
        });
        findViewById(R.id.login_clear_user_name).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mUserName.setText("");
            }
        });
        findViewById(R.id.login_forget_password).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doForgetPassword();
            }
        });
        findViewById(R.id.login_user_register).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doRegisterEvent();
            }
        });
        mUserName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                int length = NAME_LENGTH_LIMIT - s.length();
                mUserNameLimit.setText(String.valueOf(length));
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void tryLogin() {
        String userName;
        String password;
        if ((userName = checkUserName()) != null && (password = checkPassword()) != null) {
            int id = UserManage.checkLoginEvent(userName, password);
            if (id <= 0) {
                ToastUtil.makeToast(getString(R.string.login_error));
            } else {
                successLogin(id);
            }
        }
    }

    private String checkUserName() {
        String name = mUserName.getText().toString();
        if (name.equals("")) {
            ToastUtil.makeToast(getString(R.string.login_name_empty));
            return null;
        }
        return name;
    }

    private String checkPassword() {
        String password = mPassword.getText().toString();
        if (password.equals("")) {
            ToastUtil.makeToast(getString(R.string.login_password_empty));
            return null;
        }
        return StringUtil.ByteToHexString(password.getBytes());
    }

    private void doForgetPassword() {
        String name = checkUserName();
        if (name != null) {
            if (UserManage.existUserName(name)) {
                if (UserManage.getPasswordProtect(name).equals("")) {
                    ToastUtil.makeToast(getString(R.string.password_protect_question_not_exist));
                } else {
                    Intent intent = new Intent(this, SecurityQuestionActivity.class);
                    intent.putExtra(SecurityQuestionActivity.ACTION_MODE, SecurityQuestionActivity.MODE_CONFIRM);
                    intent.putExtra(DBConstants.User.NAME, name);
                    intent.putExtra(FORGET_PASSWORD, true);
                    startActivity(intent);
                    overridePendingTransition(R.anim.normal_activity_enter, R.anim.slow_activity_exit);
                }
            } else {
                ToastUtil.makeToast(getString(R.string.not_exist_name));
            }
        }
    }

    private void doRegisterEvent() {
        Intent intent = new Intent(this, RegisterActivity.class);
        startActivityForResult(intent, 1);
        overridePendingTransition(R.anim.normal_left_enter, R.anim.normal_left_exit);
    }

    private void showRegisterSuccessDialog(final int userId) {
        String title = getString(R.string.prompt);
        String message = getString(R.string.register_success);
        NormalAlertDialog alertDialog = new NormalAlertDialog(this, title, message);
        final Dialog dialog = alertDialog.getDialog();
        alertDialog.getCancel().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        alertDialog.getConfirm().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                successLogin(userId);
            }
        });
        dialog.show();
    }

    private void showErrorDialog(String errorMessage) {
        String title = getString(R.string.prompt);
        NormalAlertDialog alertDialog = new NormalAlertDialog(this, title, errorMessage);
        final Dialog dialog = alertDialog.getDialog();
        alertDialog.getCancel().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        alertDialog.getConfirm().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void successLogin(int userId) {
        if (UserManage.initUser(userId)) {
            //init for this user
            MusicInfo.initUserMusicInfo();
            startActivity(new Intent(this, MainActivity.class));
            finish();
            overridePendingTransition(R.anim.normal_left_enter, R.anim.normal_left_exit);
        } else {
            showErrorDialog(getString(R.string.login_fail));
        }
    }
}